package com.zyw.mvc.exception.handler;

import com.zyw.mvc.exception.AbstractDefaultException;
import com.zyw.mvc.exception.utils.ExceptionUtils;
import com.zyw.mvc.support.WrappedResult;

/**
 * @author vill on 16/2/2 08:33.
 * @desc
 */
public class RestDefaultExceptionHandler extends RestExceptionHandler {

    public RestDefaultExceptionHandler() {
        super(false);
    }

    /**
     * @param fullStack 是否显示堆栈信息
     */
    public RestDefaultExceptionHandler(boolean fullStack) {
        super(fullStack);
    }

    @Override
    public boolean support(Exception e) {
        return Exception.class.isAssignableFrom(e.getClass());
    }

    @Override
    public WrappedResult handleInvoke(Exception e) {
        String exMessage = e.getMessage();
        if (exMessage == null || "".equals(exMessage)) {
            logger.error(ExceptionUtils.getFullStackTrace(e));
            return WrappedResult.handleExceptionWrappedResult("服务端异常！");
        }

        if (e instanceof AbstractDefaultException) {
            logger.warn(ExceptionUtils.getMessage(e));
            if (isFullStack()) {
                return WrappedResult.handleExceptionWrappedResult(((AbstractDefaultException) e).getCode(), e.getMessage(), null);
            } else {
                return WrappedResult.handleExceptionWrappedResult(((AbstractDefaultException) e).getCode(), e.getMessage(), null);
            }
        }

        logger.warn(ExceptionUtils.getFullStackTrace(e));

        if (isFullStack()) {
            return WrappedResult.handleExceptionWrappedResult(ExceptionUtils.getFullStackTrace(e));
        } else {
            return WrappedResult.handleExceptionWrappedResult(exMessage);
        }
    }
}
